<template>
  <div class="lottery-set-container">
    <!-- 头部 -->
    <div class="header">
      <div class="header-content">
        <h1 class="title">幸运抽奖号码设置</h1>
        <p class="subtitle">设置各奖项的中奖号码</p>
      </div>
    </div>

    <!-- 奖项选择 -->
    <div class="prize-selector">
      <label class="selector-label">选择奖项：</label>
      <select v-model="selectedSettingId" @change="loadWinningNumbers" class="prize-select">
        <option value="">请选择奖项</option>
        <option v-for="setting in prizeSettings" :key="setting.id" :value="setting.id">
          {{ setting.prizeName }} (ID: {{ setting.id }})
        </option>
      </select>
    </div>

    <!-- 设置表单 -->
    <div v-if="selectedSettingId" class="settings-form">
      <!-- 当前奖项信息
      <div class="current-prize">
        <div class="prize-header">
          <div class="prize-icon">🎯</div>
          <div class="prize-info">
            <h3 class="prize-title">{{ currentPrizeName }}</h3>
            <p class="prize-desc">设置中奖号码</p>
          </div>
        </div>
      </div> -->

      <!-- 中奖号码列表 -->
      <div class="winning-numbers-section">
        <div class="section-header">
          <h4 class="section-title">中奖号码列表</h4>
          <button @click="addWinningNumber" class="add-btn">+ 添加号码</button>
        </div>
        
        <div v-if="winningNumbers.length === 0" class="empty-state">
          <p>暂无中奖号码，请添加号码</p>
        </div>
        
        <div v-else class="numbers-list">
          <div 
            v-for="(number, index) in winningNumbers" 
            :key="index" 
            class="number-item"
          >
            <div class="number-input-group">
              <label class="input-label">号码 {{ index + 1 }}</label>
              <div class="number-inputs">
                <input 
                  v-for="(digit, digitIndex) in number" 
                  :key="digitIndex"
                  v-model="winningNumbers[index][digitIndex]"
                  type="text"
                  class="number-input"
                  placeholder="0"
                  maxlength="1"
                  @input="validateDigit($event, index, digitIndex)"
                />
              </div>
            </div>
            <button @click="removeWinningNumber(index)" class="remove-btn">删除</button>
          </div>
        </div>
      </div>

      <!-- 批量操作 -->
      <div class="batch-actions">
        <button @click="clearAllNumbers" class="clear-btn">清空所有</button>
        <button @click="generateRandomNumbers" class="random-btn">随机生成</button>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div v-if="selectedSettingId" class="action-buttons">
      <button @click="saveWinningNumbers" class="save-btn" :disabled="isSaving">
        <span v-if="isSaving">保存中...</span>
        <span v-else>保存设置</span>
      </button>
      <button @click="resetNumbers" class="reset-btn">重置</button>
    </div>

    <!-- 提示信息 -->
    <div v-if="message" class="message" :class="messageType">
      {{ message }}
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { lotteryApi } from '../api/lottery.js';

// 响应式数据
const selectedSettingId = ref('');
const prizeSettings = ref([]);
const winningNumbers = ref([]);
const isSaving = ref(false);
const message = ref('');
const messageType = ref('');

// 计算属性
const currentPrizeName = computed(() => {
  const setting = prizeSettings.value.find(s => s.id === selectedSettingId.value);
  return setting ? setting.prizeName : '';
});

// 验证数字输入
const validateDigit = (event, numberIndex, digitIndex) => {
  const value = event.target.value;
  
  // 只允许输入数字
  if (value && !/^\d$/.test(value)) {
    winningNumbers.value[numberIndex][digitIndex] = '';
    return;
  }
  
  // 自动跳转到下一个输入框
  if (value && digitIndex < 2) {
    const nextInput = event.target.parentElement.children[digitIndex + 1];
    if (nextInput) {
      nextInput.focus();
    }
  }
};

// 添加中奖号码
const addWinningNumber = () => {
  winningNumbers.value.push(['', '', '']);
  showMessage('已添加新号码', 'success');
};

// 删除中奖号码
const removeWinningNumber = (index) => {
  winningNumbers.value.splice(index, 1);
  showMessage('号码已删除', 'success');
};

// 清空所有号码
const clearAllNumbers = () => {
  winningNumbers.value = [];
  showMessage('所有号码已清空', 'success');
};

// 随机生成号码
const generateRandomNumbers = () => {
  const count = Math.floor(Math.random() * 5) + 3; // 生成3-7个随机号码
  winningNumbers.value = [];
  
  for (let i = 0; i < count; i++) {
    // 生成3位随机数字，确保是3位格式
    const randomNum = Math.floor(Math.random() * 900) + 100; // 100-999
    const numberStr = randomNum.toString();
    const digits = numberStr.split('');
    
    winningNumbers.value.push(digits);
  }
  
  showMessage(`已生成${count}个随机号码`, 'success');
};

// 保存中奖号码
const saveWinningNumbers = async () => {
  try {
    isSaving.value = true;
    
    // 验证号码完整性
    const incompleteNumbers = [];
    winningNumbers.value.forEach((number, index) => {
      if (number.join('').length < 3) {
        incompleteNumbers.push(index + 1);
      }
    });
    
    if (incompleteNumbers.length > 0) {
      showMessage(`请完善第${incompleteNumbers.join('、')}个号码`, 'error');
      return;
    }
    
    // 转换为字符串数组，确保每个号码都是3位数字格式
    const numbersToSave = winningNumbers.value.map(number => {
      const numberStr = number.join('');
      // 如果不足3位，在前面补零
      return numberStr.padStart(3, '0');
    });
    
    console.log('准备保存的号码:', numbersToSave);
    
    // 调用API保存
    const response = await lotteryApi.saveWinningNumbers(selectedSettingId.value, numbersToSave);
    
    if (response.data.success) {
      showMessage('中奖号码保存成功！', 'success');
    } else {
      showMessage(response.data.message || '保存失败', 'error');
    }
  } catch (error) {
    console.error('保存中奖号码失败:', error);
    showMessage('保存失败，请重试', 'error');
  } finally {
    isSaving.value = false;
  }
};

// 重置号码
const resetNumbers = () => {
  winningNumbers.value = [];
  showMessage('号码已重置', 'success');
};

// 加载奖项设置列表
const loadPrizeSettings = async () => {
  try {
    const response = await lotteryApi.getPrizeSettings();
    prizeSettings.value = response.data || [];
  } catch (error) {
    console.error('加载奖项设置失败:', error);
    showMessage('加载奖项设置失败', 'error');
  }
};

// 加载中奖号码
const loadWinningNumbers = async () => {
  if (!selectedSettingId.value) {
    winningNumbers.value = [];
    return;
  }
  
  try {
    const response = await lotteryApi.getWinningNumbers(selectedSettingId.value);
    const numbers = response.data || [];
    
    // 处理LotteryWinningNumber对象格式
    winningNumbers.value = numbers.map(item => {
      // 如果返回的是对象，提取number字段；如果是字符串，直接使用
      const numberStr = typeof item === 'object' ? item.number || item.winningNumber : item;
      
      if (!numberStr) {
        return ['', '', ''];
      }
      
      // 将数字字符串补零到3位，例如："88" -> "088"
      const paddedNumber = numberStr.padStart(3, '0');
      const digits = paddedNumber.split('');
      
      return digits.slice(0, 3);
    });
    
    showMessage('中奖号码加载成功', 'success');
  } catch (error) {
    console.error('加载中奖号码失败:', error);
    showMessage('加载中奖号码失败', 'error');
    winningNumbers.value = [];
  }
};

// 显示消息
const showMessage = (msg, type = 'info') => {
  message.value = msg;
  messageType.value = type;
  setTimeout(() => {
    message.value = '';
  }, 3000);
};

// 组件挂载时加载奖项设置
onMounted(() => {
  loadPrizeSettings();
});
</script>

<style scoped>
.lottery-set-container {
  height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 0;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  /* 确保容器可以滚动 */
  overflow-y: auto;
  /* 防止水平滚动 */
  overflow-x: hidden;
  /* 确保滚动条显示 */
  scrollbar-width: auto;
  -webkit-overflow-scrolling: touch;
}

/* 自定义滚动条样式 */
.lottery-set-container::-webkit-scrollbar {
  width: 8px;
}

.lottery-set-container::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
}

.lottery-set-container::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.3);
  border-radius: 4px;
}

.lottery-set-container::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.5);
}

.header {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  padding: 20px 16px;
  text-align: center;
  color: white;
  /* 固定头部，不随滚动移动 */
  position: sticky;
  top: 0;
  z-index: 100;
}

.title {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
}

.subtitle {
  margin: 0;
  font-size: 14px;
  opacity: 0.8;
}

.prize-selector {
  background: white;
  margin: 16px;
  padding: 16px;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.selector-label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.prize-select {
  width: 100%;
  padding: 12px;
  border: 2px solid #e1e5e9;
  border-radius: 8px;
  font-size: 16px;
  background: white;
  transition: border-color 0.3s ease;
}

.prize-select:focus {
  outline: none;
  border-color: #667eea;
}

.settings-form {
  padding: 0 16px;
  /* 确保内容区域可以正常滚动 */
  margin-bottom: 100px; /* 为底部按钮留出空间 */
}

.current-prize {
  background: white;
  border-radius: 16px;
  margin-bottom: 16px;
  padding: 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.prize-header {
  display: flex;
  align-items: center;
}

.prize-icon {
  font-size: 32px;
  margin-right: 16px;
}

.prize-title {
  margin: 0 0 4px 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.prize-desc {
  margin: 0;
  font-size: 14px;
  color: #666;
}

.winning-numbers-section {
  background: white;
  border-radius: 16px;
  margin-bottom: 16px;
  padding: 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.add-btn {
  padding: 8px 16px;
  background: #667eea;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  cursor: pointer;
  transition: background 0.3s ease;
}

.add-btn:hover {
  background: #5a6fd8;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: #666;
}

.numbers-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.number-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 12px;
  border: 1px solid #e1e5e9;
}

.number-input-group {
  flex: 1;
}

.input-label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.number-inputs {
  display: flex;
  gap: 6px;
}

.number-input {
  width: 40px;
  height: 40px;
  border: 2px solid #e1e5e9;
  border-radius: 8px;
  text-align: center;
  font-size: 18px;
  font-weight: 600;
  background: white;
  transition: all 0.3s ease;
}

.number-input:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.remove-btn {
  padding: 8px 12px;
  background: #dc3545;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 12px;
  cursor: pointer;
  transition: background 0.3s ease;
}

.remove-btn:hover {
  background: #c82333;
}

.batch-actions {
  background: white;
  border-radius: 16px;
  margin-bottom: 16px;
  padding: 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  display: flex;
  gap: 12px;
}

.clear-btn, .random-btn {
  flex: 1;
  padding: 12px 16px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.clear-btn {
  background: #f8f9fa;
  color: #666;
}

.clear-btn:hover {
  background: #e9ecef;
}

.random-btn {
  background: #667eea;
  color: white;
}

.random-btn:hover {
  background: #5a6fd8;
}

.action-buttons {
  /* 固定底部按钮 */
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 16px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-top: 1px solid rgba(0, 0, 0, 0.1);
  display: flex;
  gap: 12px;
  z-index: 1000;
  /* 确保按钮在安全区域内 */
  padding-bottom: max(16px, env(safe-area-inset-bottom));
}

.save-btn, .reset-btn {
  flex: 1;
  padding: 16px;
  border: none;
  border-radius: 12px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  /* 确保按钮有足够的高度便于触摸 */
  min-height: 48px;
}

.save-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.save-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
}

.save-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.reset-btn {
  background: white;
  color: #666;
  border: 2px solid #e1e5e9;
}

.reset-btn:hover {
  background: #f8f9fa;
  border-color: #667eea;
  color: #667eea;
}

.message {
  position: fixed;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  padding: 12px 24px;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  z-index: 1000;
  animation: slideDown 0.3s ease;
  /* 确保消息在安全区域内 */
  top: max(20px, env(safe-area-inset-top) + 20px);
}

.message.success {
  background: #d4edda;
  color: #155724;
  border: 1px solid #c3e6cb;
}

.message.error {
  background: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
}

.message.info {
  background: #d1ecf1;
  color: #0c5460;
  border: 1px solid #bee5eb;
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateX(-50%) translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateX(-50%) translateY(0);
  }
}

/* 移动端适配 */
@media (max-width: 480px) {
  .lottery-set-container {
    /* 确保在移动端可以正常滚动 */
    -webkit-overflow-scrolling: touch;
    /* 确保滚动条在移动端也能显示 */
    overflow-y: auto;
    scrollbar-width: auto;
  }
  
  .header {
    /* 在移动端调整头部样式 */
    padding: 16px;
  }
  
  .title {
    font-size: 20px;
  }
  
  .subtitle {
    font-size: 12px;
  }
  
  .settings-form {
    /* 为底部按钮留出更多空间 */
    margin-bottom: 120px;
  }
  
  .number-inputs {
    gap: 4px;
  }
  
  .number-input {
    width: 35px;
    height: 35px;
    font-size: 16px;
  }
  
  .number-item {
    flex-direction: column;
    align-items: stretch;
  }
  
  .remove-btn {
    align-self: flex-end;
  }
  
  .action-buttons {
    /* 在移动端调整按钮样式 */
    padding: 12px 16px;
    padding-bottom: max(12px, env(safe-area-inset-bottom));
  }
  
  .save-btn, .reset-btn {
    padding: 14px;
    font-size: 15px;
    min-height: 44px;
  }
}

/* 针对iPhone X等有刘海屏的设备 */
@supports (padding: max(0px)) {
  .action-buttons {
    padding-bottom: max(16px, env(safe-area-inset-bottom));
  }
  
  .message {
    top: max(20px, env(safe-area-inset-top) + 20px);
  }
}
</style>
